import axios from 'axios'
import store from '@/store/index'
import {getOssApkInfo, getOssImgInfo, getOssApkInfoEdit, getOssFileInfo, } from "@/api/application"; //
const cdnDomain = 'https://cdn.jiaoguanyi.com'
export function ossupload(file, filePath, type, size) {//添加上传apk到oss
    return new Promise(function (resolve, reject) {
        let apkFunction = undefined
        if (!type) {//添加
            apkFunction = getOssApkInfo
        } else {//编辑
            apkFunction = getOssApkInfoEdit
        }
        let fd = new FormData();
        var filename = new Date().getTime();
        apkFunction({ userId: localStorage.getItem("ID") }).then(res => {//获取签名
            let data = res.data
            if (size > data.max_size) return reject({ code: 10086, msg: '超过上传大小，窗口关闭，请重新上传' })
            fd.append('OSSAccessKeyId', data.accessid)
            fd.append('key', 'jgy008/' + filename + localStorage.getItem("ID") + filePath)//存储文件目录
            fd.append('Signature', data.signature)
            fd.append('policy', data.policyBase64)
            fd.append('success_action_status', 200) //成功后返回的操作码
            fd.append('file', file)
            axios.post(data.host, fd, {
                onUploadProgress: progressEvent => {//进度条
                    let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
                    store.commit('user/SET_PROGRESS', Math.floor(complete))
                },
                cancelToken: new axios.CancelToken(function (c) {
                    store.commit('user/SET_CANCEL', c)
                })
            }).then(rew => {
                store.commit('user/SET_PROGRESS', 0)
                resolve(cdnDomain + '/jgy008/' + filename + localStorage.getItem("ID") + filePath)//拼接地址
            }).catch(err => {
                store.commit('user/SET_PROGRESS', 0)
                reject('上传失败, 请重新上传')
            })
        }).catch(err => {
            reject(err)
        })
    })
};


function dataURLtoBlob(dataurl) {//Base64 to Blob
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
export function ossImage(file, type) {//上传图片到oss
    return new Promise(function (resolve, reject) {
        let ext = ''
        let files = {}
        if (type) {
            ext = type
            files = file
        } else {
            files = dataURLtoBlob(file)
            ext = files.type.split('/')[1]
        }
        let fd = new FormData();
        var filename = new Date().getTime();
        //console.log('图片处理转为blob',files)
        getOssImgInfo({ userId: localStorage.getItem("ID") }).then(res => {//获取签名
            let data = res.data
            fd.append('OSSAccessKeyId', data.accessid)
            fd.append('key', 'img/' + filename + localStorage.getItem("ID") + '.' + ext)
            fd.append('Signature', data.signature)
            //fd.append('bucket', 'jgy008')
            fd.append('policy', data.policyBase64)
            fd.append('success_action_status', 200)
            fd.append('file', files)
            axios.post(data.host, fd).then(rew => {
                resolve(cdnDomain + '/img/' + filename + localStorage.getItem("ID") + '.' + ext)
            }).catch(err => {
                reject(cdnDomain + '/img/' + filename + localStorage.getItem("ID") + '.' + ext)
            })
        }).catch(err => {
            reject(err)
        })
    })
}

export function ossFile(file, type) {//上传视频、音频、文档到oss
  return new Promise(function (resolve, reject) {
    let ext = ''
    let files = {}
    if (type) {
      ext = type
      files = file
    } else {
      files = dataURLtoBlob(file)
      ext = files.type.split('/')[1]
    }
    let fd = new FormData();
    var filename = new Date().getTime();
    getOssFileInfo({ userId: localStorage.getItem("ID") }).then(res => {//获取签名
      let data = res.data
      fd.append('OSSAccessKeyId', data.accessid)
      fd.append('key', 'course/' + filename + localStorage.getItem("ID") + '.' + ext)
      fd.append('Signature', data.signature)
      //fd.append('bucket', 'jgy008')
      fd.append('policy', data.policyBase64)
      fd.append('success_action_status', 200)
      fd.append('file', files)
      axios.post(data.host, fd).then(rew => {
        resolve(cdnDomain + '/course/' + filename + localStorage.getItem("ID") + '.' + ext)
        console.log("成功")
      }).catch(err => {
        reject(cdnDomain + '/course/' + filename + localStorage.getItem("ID") + '.' + ext)
        console.log("失败")
      })
    }).catch(err => {
      reject(err)
    })
  })
}


